<?php
/**
 * Created by PhpStorm.
 * User: zhanghui
 * Date: 2018/4/24
 * Time: 17:54
 */
namespace app\common\service;

/**
 * Class PidFile   唯一进程检测
 */
class PidFile
{
    /**
     * 检测目前启动的进程数
     * @param string $pid_filename  启动脚本名称
     * @param int $pid_num 启动脚本数量
     * @return bool
     */
    public static function createPidFile( $pid_filename, $pid_num )
    {
        // 检测若为WIN直接返回正确
        if ( IS_WIN ) return true;

        // 检测当前pid目录是否存在  若不存在则创建该目录
        if (!is_dir(RUNTIME_PATH.'pid'.DIRECTORY_SEPARATOR)) {
            mkdir(RUNTIME_PATH.'pid'.DIRECTORY_SEPARATOR, 0777, true);
        }

        $pid_num = (int) $pid_num;
        if ( file_exists( RUNTIME_PATH.'pid'.DIRECTORY_SEPARATOR.$pid_filename ) )
        {

            $old_pid = trim(file_get_contents(RUNTIME_PATH.'pid'.DIRECTORY_SEPARATOR.$pid_filename));
            $old_pid = json_decode( $old_pid, true );
            $pids = [];
            // 检测正在使用的进程
            foreach ( $old_pid as $value ){
                if ( file_exists('/proc/' . $value . '/cmdline') ) {
                    $pids[] = $value;
                }
            }

            // 检测若进程数大于已启动进程数,则退出流程
            if ( count( $pids ) >= $pid_num ){
                return false;
            }
        }

        $pids[] = strval( posix_getpid() );

        file_put_contents( RUNTIME_PATH.'pid'.DIRECTORY_SEPARATOR.$pid_filename, json_encode( $pids ) );
        return true;
    }


}
                                    